import { message } from 'antd';
import { Effect } from '@/dva/types';
import deleteClassify from '@/service/image/deleteClassify';
import updateClassify from '@/service/image/updateClassify';
import createClassify from '@/service/image/createClassify';
import getClassifyList from '@/service/image/getClassifyList';
import changeClassifyState from '@/service/image/changeClassifyState';

/*
* 创建分类
* */
export const create: Effect = async (payload, { put }) => {
  put({
    type: 'imageClassify/setState',
    payload: { submitLoading: true },
  });
  try {
    await createClassify(payload);
    message.success('创建成功!');
  } catch (e) {
    message.error(e.message);
    return Promise.reject(e);
  } finally {
    put({
      type: 'imageClassify/setState',
      payload: { submitLoading: false },
    });
  }
}

/*
* 更新分类
* */
export const update: Effect = async (payload, { put }) => {
  put({
    type: 'imageClassify/setState',
    payload: { submitLoading: true },
  });
  try {
    await updateClassify(payload);
    put({
      payload: payload,
      type: 'imageClassify/updateItem'
    })
    message.success('更新成功!');
  } catch (e) {
    message.error(e.message);
    return Promise.reject(e);
  } finally {
    put({
      type: 'imageClassify/setState',
      payload: { submitLoading: false },
    });
  }
}

/*
* 获取分类列表
* */
export const queryList: Effect = async (payload, { put }) => {
  put({
    type: 'imageClassify/setState',
    payload: { loading: true },
  });
  try {
    const {
      list,
      pagination
    } = await getClassifyList(payload);
    put({
      type: 'imageClassify/setList',
      payload: { pagination, list, push: pagination.page > 1 }
    });
  } catch (e) {
    message.error(e.message);
  }
  put({
    type: 'imageClassify/setState',
    payload: { loading: false },
  });
}

/*
* 上下架
* */
export const changeState: Effect = async (payload, { put }) => {
  put({
    type: 'imageClassify/setState',
    payload: { loading: true },
  });
  const closeLoading = message.loading('加载中..');
  try {
    await changeClassifyState(payload);
    put({
      payload: payload,
      type: 'imageClassify/updateItem'
    })
  } catch (e) {
    message.error(e.message);
    return Promise.reject(e);
  }
  put({
    type: 'imageClassify/setState',
    payload: { loading: false },
  });
  closeLoading();
}

/*
* 删除
* */
export const deleteItem: Effect = async (payload, { put }) => {
  put({
    type: 'imageClassify/setState',
    payload: { loading: true },
  });
  const closeLoading = message.loading('删除中..');
  try {
    await deleteClassify(payload);
    put({
      payload: payload,
      type: 'imageClassify/deleteItem'
    })
  } catch (e) {
    message.error(e.message);
    return Promise.reject(e);
  }
  put({
    type: 'imageClassify/setState',
    payload: { loading: false },
  });
  closeLoading();
}


